function rem(designWidth, maxWidth) {
	var doc = document,
	win = window,
	docEl = doc.documentElement,
	remStyle = document.createElement("style"),
	tid;

	function refreshRem() {
		var width = docEl.getBoundingClientRect().width;
		maxWidth = maxWidth || 540;
		width>maxWidth && (width=maxWidth);
		var rem = width * 100 / designWidth;
		remStyle.innerHTML = 'html{font-size:' + rem + 'px;}';
	}

	if (docEl.firstElementChild) {
		docEl.firstElementChild.appendChild(remStyle);
	} else {
		var wrap = doc.createElement("div");
		wrap.appendChild(remStyle);
		doc.write(wrap.innerHTML);
		wrap = null;
	}
	refreshRem();

	win.addEventListener("resize", function() {
		clearTimeout(tid);
		tid = setTimeout(refreshRem, 300);
	}, false);

	win.addEventListener("pageshow", function(e) {
		if (e.persisted) {
			clearTimeout(tid);
			tid = setTimeout(refreshRem, 300);
		}
	}, false);

	if (doc.readyState === "complete") {
		doc.body.style.fontSize = "16px";
	} else {
		doc.addEventListener("DOMContentLoaded", function(e) {
			doc.body.style.fontSize = "16px";
		}, false);
	}
	document.addEventListener('DOMContentLoaded', function() {
	   FastClick.attach(document.body);
	}, false);
}
rem(750, 1024);

//项目部分
var api_init;
var baseUrl = "http://47.95.226.64/api"  //接口地址 http://47.95.226.64/doc.html
var sokectUrl = 'ws://47.95.226.64:6300/ws' //sokect地址
initIceFox(true)
apiready = function(){
	initIceFox(false);
}
function initIceFox(isPc){
	Vue ? Vue.use(iceFox) : "" //加载 冰狐 插件
	if(!isPc){
		Vue ? Vue.prototype.$env = (api.debug ? 'dev' : 'pro' ): ''; //开发环境 dev 生产环境 pro
		/* 设置frame背景*/
		api.setStatusBarStyle({
			style: 'dark',
		});
		api.setWinAttr({
			bgColor: "#F8F9FB",
		});
		api_init() //初始化Vue
		immersive();
		/**
		 * 页面公用跳转
		 * @param:添加节点class link-page
		 * @param:data-id    接收：api.pageParam.id;
		*/
		(function(){
			var linkPage = document.querySelectorAll('.link-page');
			for (var i = 0; i < linkPage.length;i++) {
				linkPage[i].addEventListener('click',function(){
					var paramString = this.dataset;
					var obj = {
						url:'',
						pageParam:{},
					};
					for (var key in paramString) {
						if (paramString.hasOwnProperty(key)) {
							key == "url" ? obj.url = paramString[key] : obj.pageParam[key] = paramString[key];
						}
					}
					api.openWin({
						name:obj.url,
						url:obj.url,
						pageParam:obj.pageParam,
					})
				},false)
			}
		})();
		/**
		 * 公用返回
		 * @param:添加公用类:back
		*/
		(function(){
			var backPage = document.querySelectorAll('.back');
			for (var i = 0; i < backPage.length;i++) {
				backPage[i].addEventListener('click',function(e){
					var timper = null;
					e.target.parentElement.classList.add('back-active');
					timper = setTimeout(function(){
						clearTimeout(timper)
						e.target.parentElement.classList.remove('back-active');
						timper = null;
						api.closeWin();
					},150)
				},true)
			}
		})();
	}else{
		setTimeout(function(){
			api_init() //初始化Vue
		},200)
	}
}
// 沉浸式
function immersive(){
	if (api.statusBarAppearance) {
		var safeArea = api.safeArea.top;
		var safeArea_bottom = api.safeArea.bottom;
		var header = document.querySelector('.header');
		var main = document.querySelector('.main');
		var footer = document.querySelector('.footer')
		if(header != null){
			var headerHeight = header.clientHeight;
			header.style.height = headerHeight + safeArea + "px";
			header.style.paddingTop = safeArea + "px";
		}
		if (main != null) {
			if (header) {
				var headerHeight = header.clientHeight;
			    main.style.paddingTop = headerHeight + "px";
			}else{
				main.style.paddingTop = safeArea + "px";
			}
		}
		if (footer != null) {
			var height2 = footer.clientHeight;
			footer.style.height = height2 + safeArea_bottom + "px";
			footer.style.paddingBottom = safeArea_bottom + "px";
		}
	}
}
//下拉加载
function btLoad(_this,methods){
	var fn = methods || "getList";
	// 上拉加载
	var timp = "";
	api.addEventListener({
	　　name:'scrolltobottom',
		extra:{threshold:20}
	}, function(ret, err){
　　　　 //上拉加载时需要加载的数据
		if (_this.list.length == _this.total) {
			return false
		}else{
			clearTimeout(timp)
			timp = setTimeout(function(){
				_this[fn]();
			},300)
		}
	});
}
//判断是否登录
function isLogin(){
	return fox.storage.get('userToken') != '';
}
//判断是否是IOS
function isIos(){
	var systemType = api.systemType;
	return systemType == "ios";
}
//根据两个时间戳计算相差小时和天数（）@param1：当前时间 @param2：结束时间
function interval(faultDate,completeTime){
	var usedTime = completeTime - faultDate;  //两个时间戳相差的毫秒数
	if (usedTime < 0) {
		return {
			m:0,
			s:0,
		}
	}
	var m = Math.floor(usedTime%(60*60) / 60);
	var s = Math.floor(usedTime%(60*60) % 60);
	if (m < 10) {
		m = "0"+m
	}
	if (s < 10) {
		s = "0"+s
	}
	return{
		m:m,
		s:s,
	}
}
function intervalMin(usedTime){
	usedTime = usedTime;
	var m = Math.floor(usedTime / 60);
	var s = Math.floor(usedTime % 60);
	if (m < 10) {
		m = "0"+m
	}
	if (s < 10) {
		s = "0"+s
	}
	return{
		m:m,
		s:s,
	}
}

function ExitApp() { //download
	var ci = 0;
	var time1, time2;
	api.addEventListener({
	  name : 'keyback'
	}, function(ret, err) {
		if(api.frames().filter(function(item){return item.name == 'download'}).length > 0){
            api.closeFrame({
				name: 'download'
			});
			return false
		}
	  if (ci == 0) {
		time1 = new Date().getTime();
		ci = 1;
		api.toast({msg:'再按一次返回键退出'});
	  } else if (ci == 1) {
		time2 = new Date().getTime();
		if (time2 - time1 < 3000) {
		api.closeWidget({
		  id : api.appId,
		  retData : {
			name : 'closeWidget'
		  },
		  silent : true
		});
		} else {
		ci = 0;
		 api.toast({msg:'再按一次返回键退出'});
		}
	  }
	});
}
  /*swiper*/
function swiper(domStr) {
	var domStr = domStr || '.swiper-container';
	var swiper = new Swiper(domStr, {
	 loop: true,
	 pagination: {
	  el: '.swiper-pagination',
	 },
	 autoplay: {
	  delay: 3000,
	  disableOnInteraction: false,
	 },
	 on: {
	   touchStart: function(event) {
		api.setFrameAttr({
		 name: api.frameName,
		 bounces: false
		});
	   },
	   touchEnd: function(event) {
		api.setFrameAttr({
		 name: api.frameName,
		 bounces: true
		});
	   },
	}
	 });
}
// 数组过滤空值
function filterAll(arr){
	var target = arr.filter(function(current){
		return current !== null && current !== undefined && current !== "";
	})
	target = target.map(function(v){
		v.goods = [];
		return v
	})
	return target;
}
//数尾补两个0 1=>1.00 , 2.2=>2.20;
function setNum2(num){
	num += '';
	num = num.replace(/[^0-9|\.]/g, '');
	if(/^0+/){num = num.replace(/^0+/, '')}
	if(!/\./.test(num)){num += '.00'}
	if(/^\./.test(num)){num = '0' + num}
	num += '00';
	num = num.match(/\d+\.\d{2}/)[0];
	return num
}
//打电话
function callPhone(phone){
	fox.showModal({
		title:"拨打电话",
		content:"确定呼叫 "+phone+" 吗?",
		icon:"widget://res/call.png",
		rightBtn:"呼叫",
		success:function(res){
            if(res.confirm){
				api.call({
					type: 'tel_prompt',
					number: phone,
				});
		    }
		}
	})
}

/*计算缓存*/
function computedCash(size){
	var size = ~~(size / 1024); //kb
	if (size > 1024 ) {
			size = ~~(size / 1024) + "MB";
	} else {
			size = size + "KB";
	}
	return size;
}
//选择图片
function chosePic(callback){
	function getPic(t,callback){
		api.getPicture({
			sourceType: t,
			encodingType: 'jpg',
			mediaValue: 'pic',
			destinationType: 'url',
			allowEdit: true,
			quality: 30,
		}, function(ret, err) {
			if (ret) {
				if(ret.data != ""){
					callback(ret.data)
				}
			}else {
				api.toast({
					msg: '请重试'
				});
			}
		});
	}
	api.actionSheet({
		cancelTitle: '取消',
		buttons: ['拍照', '从相册选择'],
		style: {
			fontNormalColor: '#000',
		}
	}, function(ret, err) {
		var index = ret.buttonIndex;
		if (index == 1) {
			var resultList = api.hasPermission({
				list:['camera']
			});
			if(resultList[0].granted==true){
				getPic('camera',callback);
			}else{
				api.requestPermission({
					list:['camera'],
					code:1
				}, function(ret, err){
					if(ret.list[0].granted){
						getPic('camera',callback);
					}
				});
			}
		} else if (index == 2) {
			var resultList = api.hasPermission({
				list:['photos']
			});
			if(resultList[0].granted==true){
				getPic('photos',callback);
			}else{
				api.requestPermission({
					list:['photos'],
					code:1
				}, function(ret, err){
					if(ret.list[0].granted){
						getPic('photos',callback);
					}
				});
			}
		}
	});
}
function chosePic2(params){
    var $defaultProps = {
		actionlist:[{name:'拍照',permise:"camera",event:"upPic"}, {name:'从相册选择',permise:"photos",event:"upPic"}],
        callBack:function(){},
	}
	params = Object.assign($defaultProps,params || {});
	var needAction = params.actionlist.map(function(v){return v.name});
	api.actionSheet({
		cancelTitle: '取消',
		buttons: needAction,
		style: {
			fontNormalColor: '#000',
		}
	}, function(ret, err) {
		var index = ret.buttonIndex;
		if(index - 1 != needAction.length){
			var targetAction = params.actionlist[index - 1];
			var needEvent = targetAction.event;
			if(needEvent == "upPic"){
			   var needPromise = targetAction.permise;
			   checkhasPermission([needPromise],function(){
				  getPic(needPromise,params.callBack,targetAction)
			   })
			}else{
				params.callBack(targetAction)
			}
		}
	});
	function getPic(t,callback,targetAction){
		api.getPicture({
			sourceType: t,
			encodingType: 'jpg',
			mediaValue: 'pic',
			destinationType: 'url',
			allowEdit: true,
			quality: 30,
		}, function(ret, err) {
			if (ret) {
				if(ret.data != ""){
					targetAction.pic = ret.data;
					callback(targetAction)
				}
			}else {
				api.toast({
					msg: '请重试'
				});
			}
		});
	}
}
//wxPlus 登录
function wxPlusLogin(callback){
	var wxPlus = api.require('wxPlus');
	wxPlus.isInstalled(function(ret, err) {
		if (ret.installed) {
			wxPlus.auth({
				apiKey: ''
			}, function(ret, err) {
				if (ret.status) {
					var authCode = ret.code; //授权Code
					wxPlus.getToken({
						apiKey: '',
						apiSecret: '',
						code: authCode,
					}, function(ret, err) {
						if (ret.status) {
							var openId = ret.openId;
							var accessToken = ret.accessToken;
							wxPlus.getUserInfo({
								accessToken: accessToken,
								openId: openId,
							}, function(ret, err) {
								if (ret.status) {
									callback(ret)
								} else {
									fox.showToast({title:"微信用户信息获取失败"})
								}
							});
						}else{
							fox.showToast({title:"微信登录凭证获取失败"})
						}
					});
				} else {
					fox.showToast({title:"登录失败"})
				}
			});
		} else {
			fox.showToast({title:"请先安装微信客户端"})
		}
	});
}
//普通时间戳处理
function  dateFormat(timestamp, formats) {
    // formats格式包括
    // 1. Y-m-d
    // 2. Y-m-d H:i:s
    // 3. Y年m月d日
    // 4. Y年m月d日 H时i分
    formats = formats || 'Y-m-d';
    var zero = function (value) {
        if (value < 10) {
            return '0' + value;
        }
        return value;
    };
    var myDate = timestamp ? new Date(timestamp): new Date();
    var year = myDate.getFullYear();
    var month = zero(myDate.getMonth() + 1);
    var day = zero(myDate.getDate());
    var hour = zero(myDate.getHours());
    var minite = zero(myDate.getMinutes());
    var second = zero(myDate.getSeconds());
    return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
        return ({
            Y: year,
            m: month,
            d: day,
            H: hour,
            i: minite,
            s: second
        })[matches];
    });
};
//权限检测并获取
function checkhasPermission(permissionArr,callBack){
	var resultList = api.hasPermission({
		list:permissionArr,
	});
	//判断用户没有哪个权限
	var noPermission = resultList.filter(function(v){
		return v.granted ? "" :v
	})
	if (noPermission.length != 0) {
		getPermission(noPermission,callBack);
	}else{
		callBack();
	}
}
//申请权限
function getPermission(perList,callBack){
	if (perList.length == 0) {
		return false
	}
	var perName = perList.map(function(v){return v.name});
	api.confirm({
		title: '提示',
		msg: '检测到您有'+translatePermission(perName[0])+'权限未开启是否前往授权',
		buttons:['确定', '取消']
	},function(ret,err){
		if(ret.buttonIndex == 1){
			api.requestPermission({
				list:perName,
				code:1
			}, function(ret, err){
				var noPermission = ret.list.filter(function(v){return v.granted && !v.never ? "" : v})
				if(noPermission.length == 0){
					callBack();
				}else{
					getPermission(noPermission,callBack)
				}
			});
		}
	});
}
//权限翻译，把对应英文转换成中文
function translatePermission(name){
	var arr = [
		{name:"location",chinese:"定位"},
		{name:"locationAlways",chinese:"持续定位"},
		{name:"notification",chinese:"通知"},
		{name:"phone-call",chinese:"电话"},
		{name:"storage",chinese:"存储"},
	]
	return arr.filter(function(v){return v.name == name})[0].chinese;
}
function handerPage(listLen){
	return Math.ceil(listLen / 10) + 1;
}
//毫秒转化 多少小时多少分钟多秒
function timpsTohms(timp){
	var h = Math.floor(timp / (1000 * 60 * 60)); //小时
	var m = Math.floor(timp % (1000 * 60 * 60) / (1000 * 60)); //分钟
	var s = Math.floor(timp % (1000 * 60 * 60) % (1000 * 60) / 1000)
	if(h< 10){
		h = "0"+h
	}
	if(m< 10){
		m = "0"+m
	}
	if(s< 10){
		s = "0"+s
	}
	return h+":"+m+":"+s
}
//单选
function singleCheck (list,idx) {
    list = list.map(function(v,i){
        v.status = i == idx;
        return v
    })
    return list
}
function miilTomi(timps){
	var m = Math.floor(timps / (1000 * 60));
	var s = Math.floor(timps % (1000 * 60) / 1000);
	m = m < 10 ? "0"+m : m;
	s = s < 10 ? "0"+s : s;
	return m+":"+s
}
//秒 =》分钟 转换 
function miTohouse(timps){
	if(timps == 0){
		return {s:timps,txt:"秒"}
	}
	var m = timps / 60;
	if(m < 1){
		return {s:timps,txt:"秒"}
	}else{
		m = Math.floor(m)
		var sSp = Math.floor((timps % 60 / 60) * 10) / 10;
		return {s:m + sSp,txt:"分钟"}
	}
}
//当去当前屏幕中心点的坐标
function getWinCenterPostioin(){
	var docWh = document.documentElement.getBoundingClientRect();
	return {
	   w:docWh.width / 2,
	   h:docWh.height / 2,
	}
}
function formTransDate(date){
    return date.split('-').map(function(v){ return v < 10 && v.toString().length < 2 ? '0'+v : v }).join('-')
}
//date 处理日期，防止组件匹配失败  2020-07-08 => 2020-7-8
function dateTransForm(date){
	return date.split('-').map(function(v){ return v[0] == 0 ? v.substring(1)  : v }).join('-')
}
//进入音频播放界面
function toAudioPage(url,id){
	var lastAudioId = fox.storage.get('lastAudioId');
	var isLoad = id != lastAudioId;
	fox.storage.set('lastAudioId',id)
	fox.eventCenter.trigger('audiobtnState',{status:true,url:url,id:id}) //打开Index页面的
	fox.navigateTo({
		url:url,
		singleInstance:true,
		isLoad:isLoad,
	})
}
//判断frame是否存在
function hasFrame(name){
	var frames = api.frames();
	var filterResult = frames.filter(function(item){return item.name == name});
	return filterResult.length > 0;
}
//分割App被调起的Url
function getAppQuery(url) {
	if (!url) {
	return false
	}
	var obj = {};
	var urlArr = url.split('//');
	obj.url = urlArr[0];
	if (urlArr.length == 2) {
		var param = urlArr[1].split('&');
		var xinObj = {};
		for (var i = 0; i < param.length; i++) {
			var eleArr = param[i].split('=');
			xinObj[eleArr[0]] = eleArr[1];
		};
		obj.params = xinObj;
	}
	return obj;
}
function sendNoticeBar(params){
	api.notification({
		notify: {
			title: params.title || "提示",
			content: params.content || "提醒",
			extra: params.extra || {},
			updateCurrent: true,
		}, 
		light:true,
	});
}